import json
import asyncio
import websockets
import aiohttp
from config import CONFIG
import json
import re
import os
from coze_agent_api import create_conversation, create_message, get_chat_result, create_chat

def parse_message_content(result):
    """解析消息内容，提取多条 content 和 uid"""
    try:
        # 从 result 中获取 content 字段
        raw_content = result.get('content', '')
        
        # 使用正则表达式提取所有的 content 和 uid 对
        content_uid_pairs = re.findall(r'{content:"([^"]*)", uid:"([^"]*)"', raw_content)
        
        if not content_uid_pairs:
            print("[警告] 未找到任何有效的消息对")
            return []
            
        messages = []
        for content, uid in content_uid_pairs:
            messages.append({
                "content": content,
                "uid": uid
            })
            
        print(f"[调试] 解析结果 - 消息数量: {len(messages)}")
        for msg in messages:
            print(f"[调试] 消息: content: {msg['content']}, uid: {msg['uid']}")
            
        return messages
        
    except Exception as e:
        print(f"[错误] 解析消息内容失败: {str(e)}")
        return []


# 使用示例：
# result = {"content": "{content:\"lalalalaala\", uid:\"123\"}", ...}
# parsed = parse_message_content(result)
# print(parsed['content'])  # 输出: lalalalaala
# print(parsed['uid'])      # 输出: 123


async def handle_assistant_reply(session, parsed_content):
    """处理助手回复，查找会话ID并发送消息"""
    try:
        # 1. 从文件读取 uid 和 conversation_id 的映射
        mapping_file = "conversation_mapping.json"
        if not os.path.exists(mapping_file):
            raise Exception(f"映射文件 {mapping_file} 不存在")
        
        with open(mapping_file, 'r', encoding='utf-8') as f:
            mappings = json.load(f)
        
        # 2. 查找对应的 conversation_id
        uid = parsed_content['uid']
        if uid not in mappings:
            raise Exception(f"找不到 UID {uid} 对应的会话ID")
        
        conversation_id = mappings[uid]
        print(f"[调试] 找到会话ID: {conversation_id} (UID: {uid})")
        
        # 3. 创建助手消息
        url = f'https://api.coze.cn/v1/conversation/message/create'
        headers = {
            "Authorization": f"Bearer {CONFIG['api_token']}",
            "Content-Type": "application/json"
        }
        
        params = {
            "conversation_id": conversation_id
        }
        
        data = {
            "role": "assistant",  # 以助手身份发送
            "content": parsed_content['content'],
            "content_type": "text"
        }
        
        print(f"[调试] 发送助手消息: {data}")
        
        async with session.post(url, headers=headers, params=params, json=data) as response:
            result = await response.json()
            print(f"[调试] 发送消息响应: {result}")
            if isinstance(result, list) and len(result) > 0:
                response_data = result[0]
            elif isinstance(result, dict):
                response_data = result
            else:
                print("[错误] 返回数据格式不正确", result)
                return None
            
            code = response_data.get('code')
            if code != 0:
                raise Exception(f"发送消息失败: {result}")
            
            return result['data']['id']
            
    except Exception as e:
        print(f"[错误] 处理助手回复失败: {str(e)}")
        return None

async def handle_websocket(websocket, path=None):
    print(f"[连接] 有新的客户端连接，路径: {path}")
    try:
        async for message in websocket:
            # 输出接收到的原始消息
            print("[接收到原始消息]", message)
            try:
                data = json.loads(message)
                print("[接收到数据]", data)
            except json.JSONDecodeError as e:
                print("[错误] JSON解析失败:", e)
                continue

            # 简单回显，将消息返回给客户端
            response_text = f"收到你的消息: {data}"
            await websocket.send(response_text)
    except websockets.exceptions.ConnectionClosed as e:
        print("[连接关闭]", e)

async def main():
    host = CONFIG.get("host", "127.0.0.1")
    port = CONFIG.get("port", 8001)
    server = await websockets.serve(
        handle_websocket, host, port, ping_interval=20, ping_timeout=30
    )
    print(f"[服务启动] ws://{host}:{port}")
    await server.wait_closed()

if __name__ == "__main__":
    asyncio.run(main())